package com.kyc.kycxkplaygame.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.kyc.kycxkplaygame.R;
import com.kyc.kycxkplaygame.dbutils.IntImp.AlasbusyIApi;
import com.kyc.kycxkplaygame.dbutils.inter.HttpQuestResultListener;
import com.kyc.kycxkplaygame.entity.RegisterUserInfoBean;
import com.kyc.kycxkplaygame.entity.UserInfoBean;
import com.kyc.kycxkplaygame.entity.findUserNameBean;
import com.kyc.kycxkplaygame.greendao.LevelPassBean;
import com.kyc.kycxkplaygame.greendao.PropInfoBean;
import com.kyc.kycxkplaygame.greendao.UserInfoGdBean;
import com.kyc.kycxkplaygame.greendao.manager.LevelInfoManager;
import com.kyc.kycxkplaygame.greendao.manager.PropInfoManager;
import com.kyc.kycxkplaygame.greendao.manager.UserInfoManager;
import com.kyc.kycxkplaygame.util.SharedPreferencesUtils;
import com.zhy.android.percent.support.PercentLinearLayout;
import es.dmoral.toasty.Toasty;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends Activity implements HttpQuestResultListener {

    private TextView login_pwd;
    private TextView login_yzm;
    private PercentLinearLayout yzm_linLayout;
    private PercentLinearLayout pwd_linLayout;
    private EditText pwd_edit_txt;
    private EditText phone_edit_txt;
    private EditText yzm_edit_txt;
    private TextView yzm_daojishi_txt;

    private int time = 60;

    private Handler mHandler = new Handler();
    private AlasbusyIApi alasbusyIApi;
    private String pwd;
    private String phone;
    private ImageView login_btn;
    private ImageView register_btn;
    private TextView register;
    private PercentLinearLayout register_layout;
    private PercentLinearLayout login_layout;
    private EditText register_phone_edit_txt;
    private EditText register_yzm_edit_txt;
    private TextView register_yzm_daojishi_txt;
    private EditText register_pwd_edit_txt;
    private PercentLinearLayout login_title_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setFinishOnTouchOutside(false);
        setContentView(R.layout.activity_login);
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.alpha = 1f;
        window.setAttributes(layoutParams);

        initView();

        initListener();
    }

    private void initView() {
        login_pwd = findViewById(R.id.login_pwd);
        login_yzm = findViewById(R.id.login_yzm);

        yzm_linLayout = findViewById(R.id.yzm_linLayout);
        pwd_linLayout = findViewById(R.id.pwd_linLayout);

        phone_edit_txt = findViewById(R.id.phone_edit_txt);
        pwd_edit_txt = findViewById(R.id.pwd_edit_txt);

        yzm_edit_txt = findViewById(R.id.yzm_edit_txt);
        yzm_daojishi_txt = findViewById(R.id.yzm_daojishi_txt);
        login_btn = findViewById(R.id.login_btn);

        register_btn = findViewById(R.id.register_btn);

        register = findViewById(R.id.register);
        register_layout = findViewById(R.id.register_layout);
        login_layout = findViewById(R.id.login_layout);
        login_title_layout = findViewById(R.id.login_title_layout);

        register_phone_edit_txt = findViewById(R.id.register_phone_edit_txt);
        register_yzm_edit_txt = findViewById(R.id.register_yzm_edit_txt);
        register_yzm_daojishi_txt = findViewById(R.id.register_yzm_daojishi_txt);
        register_pwd_edit_txt = findViewById(R.id.register_pwd_edit_txt);

        pwd_linLayout.setVisibility(View.VISIBLE);
        yzm_linLayout.setVisibility(View.GONE);
        login_layout.setVisibility(View.VISIBLE);

        alasbusyIApi = AlasbusyIApi.getInstance(this);
        alasbusyIApi.setHttpQuestResultListener(this);
    }


    private void initListener() {
        findViewById(R.id.login_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
                intent.putExtra("status", "fail");
                setResult(1101, intent);*/
                LoginActivity.this.finish();
                // WelcomeActivity.instance.finish();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register_layout.setVisibility(View.VISIBLE);
                login_layout.setVisibility(View.GONE);
                login_title_layout.setVisibility(View.GONE);
            }
        });

        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                phone = phone_edit_txt.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    return;
                } else {
                    if (pwd_linLayout.getVisibility() == View.VISIBLE && yzm_linLayout.getVisibility() == View.GONE) {
                        pwd = pwd_edit_txt.getText().toString();
                        if (TextUtils.isEmpty(pwd)) {
                            return;
                        }
                        alasbusyIApi.findUserName(phone);
                    } else if (yzm_linLayout.getVisibility() == View.VISIBLE) {
                        String yzm = yzm_edit_txt.getText().toString();
                        if (TextUtils.isEmpty(yzm)) {
                            return;
                        }

                        String pwd = pwd_edit_txt.getText().toString();
                        if (TextUtils.isEmpty(pwd)) {
                            Toasty.warning(LoginActivity.this, "请输入登录密码.", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        alasbusyIApi.findUserName(phone);
                    }
                }
            }
        });

        login_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwd_linLayout.setVisibility(View.GONE);
                yzm_linLayout.setVisibility(View.VISIBLE);
                yzm_daojishi_txt.setEnabled(true);
                login_yzm.setBackgroundColor(getResources().getColor(R.color.c_b6732c));
                login_yzm.setTextColor(getResources().getColor(R.color.white));
                login_pwd.setBackgroundColor(getResources().getColor(R.color.white));
                login_pwd.setTextColor(getResources().getColor(R.color.c_b6732c));
            }
        });
        login_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwd_linLayout.setVisibility(View.VISIBLE);
                yzm_linLayout.setVisibility(View.GONE);
                yzm_daojishi_txt.setEnabled(false);
                login_pwd.setBackgroundColor(getResources().getColor(R.color.c_b6732c));
                login_pwd.setTextColor(getResources().getColor(R.color.white));
                login_yzm.setBackgroundColor(getResources().getColor(R.color.white));
                login_yzm.setTextColor(getResources().getColor(R.color.c_b6732c));
            }
        });

        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(register_phone_edit_txt.getText().toString())) {
                    register_phone_edit_txt.setError("请输入手机号.");
                    return;
                } else if (TextUtils.isEmpty(register_pwd_edit_txt.getText().toString())) {
                    register_pwd_edit_txt.setError("请输入密码.");
                    return;
                }
                alasbusyIApi.usersRegister(register_phone_edit_txt.getText().toString(), register_pwd_edit_txt.getText().toString());
            }
        });

        yzm_daojishi_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO 发送手机验证码
                if (TextUtils.isEmpty(phone_edit_txt.getText().toString())) {
                    phone_edit_txt.setError("请输入手机号.");
                    return;
                }
                /*List<UserInfoGdBean> infoUsername = UserInfoManager.getInstance().getInfoUsername(phone_edit_txt.getText().toString());
                if (infoUsername.size() > 0) {
                    pwd_linLayout.setVisibility(View.GONE);
                } else {
                    pwd_linLayout.setVisibility(View.VISIBLE);
                }*/
                mHandler.postDelayed(yzmDjsRunnable, 1000);
            }
        });

        register_yzm_daojishi_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO 发送手机验证码
                if (TextUtils.isEmpty(register_phone_edit_txt.getText().toString())) {
                    register_phone_edit_txt.setError("请输入手机号.");
                    return;
                }
                /*List<UserInfoGdBean> infoUsername = UserInfoManager.getInstance().getInfoUsername(phone_edit_txt.getText().toString());
                if (infoUsername.size() > 0) {
                    pwd_linLayout.setVisibility(View.GONE);
                } else {
                    pwd_linLayout.setVisibility(View.VISIBLE);
                }*/
                mHandler.postDelayed(RegisteryzmDjsRunnable, 1000);
            }
        });
    }

    Runnable yzmDjsRunnable = new Runnable() {
        @Override
        public void run() {
            if (time <= 1) {
                yzm_daojishi_txt.setEnabled(true);
                yzm_daojishi_txt.setText("获取验证码");
                time = 60;
                mHandler.removeCallbacks(yzmDjsRunnable);
            } else {
                time = time - 1;
                yzm_daojishi_txt.setEnabled(false);
                yzm_daojishi_txt.setText(time + "S后重发");
                mHandler.postDelayed(yzmDjsRunnable, 1000);
            }
        }
    };

    Runnable RegisteryzmDjsRunnable = new Runnable() {
        @Override
        public void run() {
            if (time <= 1) {
                register_yzm_daojishi_txt.setEnabled(true);
                register_yzm_daojishi_txt.setText("获取验证码");
                time = 60;
                mHandler.removeCallbacks(yzmDjsRunnable);
            } else {
                time = time - 1;
                register_yzm_daojishi_txt.setEnabled(false);
                register_yzm_daojishi_txt.setText(time + "S后重发");
                mHandler.postDelayed(yzmDjsRunnable, 1000);
            }
        }
    };

    @Override
    public void onError(Object e) {
        Toasty.error(LoginActivity.this, "连接失败!", Toast.LENGTH_SHORT).show();
    }

    //public String[] testProp = {"体力", "葡萄", "草莓", "西柚", "青苹果", "西瓜", "提示", "炸弹", "时间"};

    @Override
    public void onSuccess(Object object) {
        if (object instanceof findUserNameBean) {
            findUserNameBean findUserNameBean = (findUserNameBean) object;
            if (findUserNameBean.getCode() == 200) {
                Log.i("http", "findUsername == " + findUserNameBean.getCode());
                alasbusyIApi.userLogin(phone, pwd);
            } else {
                /*Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
                intent.putExtra("phone", phone);
                intent.putExtra("pwd", pwd);
                intent.putExtra("status", "success");
                setResult(1101, intent);
                LoginActivity.this.finish();*/
                alasbusyIApi.usersRegister(phone, pwd);
            }
        }


        if (object instanceof UserInfoBean) {
            UserInfoBean userInfoBean = (UserInfoBean) object;
            if (userInfoBean.getCode() == 200) {
                UserInfoBean.LogininfoBean logininfo = userInfoBean.getLogininfo();
                Log.i("KYCC", "logininfo === " + logininfo.getUserName());
                if (logininfo.getUserLevelInfo() != null) {
                    List<UserInfoBean.LogininfoBean.UserLevelInfoBean> userLevelInfo = logininfo.getUserLevelInfo();
                    if (userLevelInfo.size() > 0) {
                        for (UserInfoBean.LogininfoBean.UserLevelInfoBean levelBean : userLevelInfo) {
                            final LevelPassBean passBean = new LevelPassBean();
                            passBean.setId(levelBean.getLevelID());
                            passBean.setLevel(String.valueOf(levelBean.getLevel()));
                            passBean.setPutaoNum(levelBean.getGrepNum());
                            passBean.setPassfraction(levelBean.getFraction());
                            passBean.setLianjicount(levelBean.getBatter());
                            passBean.setStarCount(levelBean.getStartCount());
                            passBean.setStatus("已通关");

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    LevelInfoManager.getInstance().insertOrUpdate(passBean);
                                }
                            }).start();
                        }
                    }
                }

                final UserInfoGdBean userInfoGdBean = new UserInfoGdBean();
                userInfoGdBean.setUserphone(logininfo.getUserName());
                userInfoGdBean.setUserpwd(pwd);
                userInfoGdBean.setId((long) (logininfo.getUserID()));
                userInfoGdBean.setCode(userInfoBean.getCode());
                userInfoGdBean.setWxName(String.valueOf(logininfo.getWxName()));
                userInfoGdBean.setRegisDate(String.valueOf(logininfo.getRegistDate()));
                userInfoGdBean.setUpdateDate(String.valueOf(logininfo.getUpdateDate()));
                userInfoGdBean.setLevel(String.valueOf(logininfo.getNowLevel()));

                List<UserInfoBean.LogininfoBean.UserPropInfoBean> propInfo = logininfo.getUserPropInfo();
                if (propInfo.size() > 0) {
                    final List<PropInfoBean> list = new ArrayList<>();
                    for (UserInfoBean.LogininfoBean.UserPropInfoBean userprop : propInfo) {
                        PropInfoBean propInfoBean = new PropInfoBean();
                        propInfoBean.setId(userprop.getUpID());
                        propInfoBean.setUserName(logininfo.getUserName());
                        propInfoBean.setPropName(userprop.getPropName());
                        propInfoBean.setPropNum(userprop.getPropNum());
                        list.add(propInfoBean);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            UserInfoManager.getInstance().insertUserInfo(userInfoGdBean);
                            PropInfoManager.getInstance().insertPropInfo(list);
                        }
                    }).start();
                }

                SharedPreferencesUtils.setParam(LoginActivity.this, "phone", phone);
                SharedPreferencesUtils.setParam(LoginActivity.this, "pwd", pwd);
                startActivity(new Intent(LoginActivity.this, LevelActivity.class));
                LoginActivity.this.finish();
                WelcomeActivity.instance.finish();
            } else {
                Toasty.warning(LoginActivity.this, userInfoBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        if (object instanceof RegisterUserInfoBean) {
            RegisterUserInfoBean registerUserInfoBean = (RegisterUserInfoBean) object;
            if (registerUserInfoBean.getCode() == 200) {
                RegisterUserInfoBean.UserInfoBean logininfo = registerUserInfoBean.getUserInfo();
                Log.i("KYCC", "registerlogininfo === " + logininfo.getUserName());
                final UserInfoGdBean userInfoGdBean = new UserInfoGdBean();
                userInfoGdBean.setUserphone(logininfo.getUserName());
                userInfoGdBean.setUserpwd(pwd);
                //int infoCount = UserInfoManager.getInstance().getUserInfoCount();
                userInfoGdBean.setId((long) (logininfo.getUserID()));
                userInfoGdBean.setCode(registerUserInfoBean.getCode());
                userInfoGdBean.setWxName(String.valueOf(logininfo.getWxName()));
                userInfoGdBean.setRegisDate(String.valueOf(logininfo.getRegistDate()));
                userInfoGdBean.setUpdateDate(String.valueOf(logininfo.getUpdateDate()));
                userInfoGdBean.setLevel(String.valueOf(logininfo.getNowLevel()));

                List<RegisterUserInfoBean.UserInfoBean.UserPropInfoBean> propInfo = logininfo.getUserPropInfo();
                if (propInfo.size() > 0) {
                    final List<PropInfoBean> list = new ArrayList<>();
                    for (RegisterUserInfoBean.UserInfoBean.UserPropInfoBean userprop : propInfo) {

                        PropInfoBean propInfoBean = new PropInfoBean();
                        propInfoBean.setId(userprop.getUpID());
                        propInfoBean.setUserName(logininfo.getUserName());
                        propInfoBean.setPropName(userprop.getPropName());
                        propInfoBean.setPropNum(userprop.getPropNum());
                        list.add(propInfoBean);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            UserInfoManager.getInstance().insertUserInfo(userInfoGdBean);
                            PropInfoManager.getInstance().insertPropInfo(list);
                        }
                    }).start();
                }
                SharedPreferencesUtils.setParam(LoginActivity.this, "phone", phone);
                SharedPreferencesUtils.setParam(LoginActivity.this, "pwd", pwd);
                startActivity(new Intent(LoginActivity.this, LevelActivity.class));
                LoginActivity.this.finish();
                WelcomeActivity.instance.finish();
            } else if (registerUserInfoBean.getCode() == 300) {
                Toasty.warning(LoginActivity.this, registerUserInfoBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onQuestErroCode(Object object) {
        if (object instanceof RegisterUserInfoBean) {
            RegisterUserInfoBean registerUserInfoBean = (RegisterUserInfoBean) object;
            //if (registerUserInfoBean.getCode() == -200) {
            Toasty.error(LoginActivity.this, registerUserInfoBean.getMessage(), Toast.LENGTH_SHORT).show();
            // }
        }
        if (object instanceof UserInfoBean) {
            UserInfoBean userInfoBean = (UserInfoBean) object;
            Toasty.error(LoginActivity.this, userInfoBean.getMessage(), Toast.LENGTH_SHORT).show();
        }

        if (object instanceof findUserNameBean) {
            findUserNameBean findUserNameBean = (findUserNameBean) object;
            if (findUserNameBean.getCode() == -200) {
                //Toasty.error(LoginActivity.this, findUserNameBean.getMessage(), Toast.LENGTH_SHORT).show();
                //alasbusyIApi.usersRegister(phone, pwd);
                login_btn.setVisibility(View.GONE);
                register_btn.setVisibility(View.VISIBLE);
            }
        }

    }
}
